package nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;

/**
 * @author fengbo
 */
public class NioServer {

    public void init(int port) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        serverSocketChannel.bind(new InetSocketAddress(port));

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (SelectionKey key : selectionKeys) {
                if (key.isAcceptable()) {
                    SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
                    if (channel != null) {
                        System.out.println(channel.getRemoteAddress() + " connected!");
                        channel.configureBlocking(false);
                        channel.register(selector, SelectionKey.OP_READ);
                    }
                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buff = ByteBuffer.allocate(1024);
                    channel.read(buff);
                    buff.flip();
                    CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
                    String msg = decoder.decode(buff).toString();
                    System.out.println(msg);
                    key.attach(msg);
                    key.interestOps(SelectionKey.OP_WRITE);
                } else if (key.isWritable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    String msg = key.attachment().toString();
                    channel.write(ByteBuffer.wrap(("resp: " + msg).getBytes()));
                    key.interestOps(SelectionKey.OP_READ);
//                    channel.close();
                }
            }
        }
    }

    @Test
    public void testServer1() throws IOException {
        init(8080);
    }

    @Test
    public void testServer2() throws IOException {
        init(8081);
    }
}
